package tech.mhuang.pacebox.springboot.autoconfiguration.elasticsearch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tech.mhuang.pacebox.core.check.CheckAssert;
import tech.mhuang.pacebox.elasticsearch.admin.ESFramework;
import tech.mhuang.pacebox.elasticsearch.admin.external.IESExternal;
import tech.mhuang.pacebox.springboot.autoconfiguration.ConfigConsts;
import tech.mhuang.pacebox.springboot.core.spring.start.SpringContextHolder;

/**
 * es构建类
 *
 * @author mhuang
 * @since 1.0.0
 */
@Configuration
@ConditionalOnClass(ESFramework.class)
@EnableConfigurationProperties(ESProperties.class)
@ConditionalOnProperty(prefix = ConfigConsts.ELASTICSEARCH, name = ConfigConsts.ENABLE, havingValue = ConfigConsts.TRUE)
@Slf4j
public class ESAutoConfiguration {

    private final ESProperties properties;

    public ESAutoConfiguration(ESProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public IESExternal esExternal() {
        return new SpringESExternal();
    }

    /**
     * 确保SpringContextHolader加载到spring 容器
     *
     * @param esExternal          es扩展
     * @param springContextHolder spring全局
     * @return es框架
     */
    @Bean
    @ConditionalOnMissingBean
    public ESFramework esFramework(IESExternal esExternal, SpringContextHolder springContextHolder) {
        CheckAssert.check(this.properties, "es properties invalid...");
        CheckAssert.check(springContextHolder, "SpringContextHolder不存在、请设置mhuang.holder.enable=true");
        ESFramework framework = new ESFramework(this.properties);
        framework.external(esExternal);
        framework.start();
        return framework;
    }
}
